package com.ssy.lingxi.scheduler.serviceimpl;

import com.ssy.lingxi.scheduler.service.IScheduleDataInitService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * 定时任务服务初始化类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-07-12
 */
@Service
public class ScheduleDataInitServiceImpl implements IScheduleDataInitService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 创建Quartz表结构
     */
    @Override
    public void createQuartzTables() {
        if(tableExist()) {
            return;
        }

        String ddlSql = readDdlFileContent();
        if(StringUtils.hasLength(ddlSql)) {
            jdbcTemplate.execute(ddlSql);
        }
    }

    /**
     * 读取Resource目录下的sql脚本文件
     * @return sql文件中的所有sql语句
     */
    private String readDdlFileContent() {
        final String quartzInitFileName = "quartz-db-init.sql";
        org.springframework.core.io.Resource resource = new ClassPathResource(quartzInitFileName);
        try {
            InputStream inputStream = resource.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }

            inputStream.close();
            bufferedReader.close();
            return sb.toString();
        } catch (Exception e) {
            System.err.println("创建Quartz表错误：" + e.getMessage());
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 判断表是否存在
     * @return 是-true，否-false
     */
    private boolean tableExist() {
        String sql = "select count(*) as total from pg_class where relname = 'qrtz_blob_triggers'";
        SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql);
        long total = 0;
        while (sqlRowSet.next()) {
            total = sqlRowSet.getLong("total");
        }

        return total > 0;
    }
}
